<template>
  <div id="app-container" style="padding:20px">
    <div id="container" style="background-color:white;">
    <div class="form-list">
      <el-form ref="form" :model="formList" label-width="80px" :rules="rules">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="formList.oldPassword" type="password" clearable show-password placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formList.newPassword" type="password" clearable show-password placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="formList.confirmPassword" type="password" clearable show-password placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="color: #fff; background-color: #586cb1; border-color: #586cb1" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  </div>
</template>

<script>

import  {updatePassword} from '@/api/user'

export default {
  name: 'Password',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formList.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formList: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度应为 6 到 12 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度应为 6 到 12 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 12, message: '长度应为 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 调用修改密码接口
          updatePassword(this.formList).then(async res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            await this.$store.dispatch('user/logout')
            this.$router.push(`/login?redirect=${this.$route.fullPath}`)
          })
        } else {
          this.$message.error('请检查输入')
        }
      })
    }
  },
}
</script>

<style scoped>
#container {
  padding: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.form-list {
  width: 300px;
  height: 300px;
}
</style>
